package com.neteast.androidclient.newscenter.activity;

import java.net.URL;
import org.xmlpull.v1.XmlPullParser;
import com.neteast.androidclient.newscenter.NewsCenter;
import com.neteast.androidclient.newscenter.R;
import com.neteast.androidclient.newscenter.service.DownLoadService;
import com.neteast.androidclient.newscenter.service.NetService;
import com.neteast.androidclient.newscenter.service.WidgetService;
import com.neteast.androidclient.newscenter.util.ConfigUtil;
import com.neteast.androidclient.newscenter.util.LoginUtil;
import android.app.Activity;
import android.app.ActivityGroup;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.ContextMenu;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.MotionEvent;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

public class MainActivity extends ActivityGroup implements OnClickListener {
	
	private NewsCenter newsCenter;
	private LinearLayout container;
	private TextView sysNews;
	private TextView appNews;
	private TextView userNews;
	private int userId;
	UpgradeInfo info;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.newscenter_main);
		getWindow().setGravity(Gravity.LEFT);
		getWindow().setLayout(449, 768);
		newsCenter = (NewsCenter) getApplication();
		newsCenter.widgetService.hiddenNewsList();
		newsCenter.mainActivity=this;
		refreshUploadInfo("http://218.108.168.46:8888/newscenter/upgrade.xml");
	}

	private void setinAnimation() {
		main.startAnimation(inAnimation);
	}
	private void setOutAnimation(){
		main.startAnimation(outAnimation);
	}
	private void init() {
		userId = LoginUtil.getUserId(this);
		context = this;
		container = (LinearLayout) findViewById(R.id.container);
		sysBtn = (RadioButton) findViewById(R.id.btn_sys);
		appBtn = (RadioButton) findViewById(R.id.btn_app);
		userBtn = (RadioButton) findViewById(R.id.btn_user);
		RadioButton configBtn = (RadioButton) findViewById(R.id.btn_config);
		RadioButton userCenterBtn = (RadioButton) findViewById(R.id.btn_usercenter);
		
		main = findViewById(R.id.newscenter_main);
		sysNews = (TextView) findViewById(R.id.sys_news);
		appNews = (TextView) findViewById(R.id.app_news);
		userNews = (TextView) findViewById(R.id.user_news);
		
		Button hander=(Button) findViewById(R.id.hander);
		
		sysBtn.setOnClickListener(this);
		appBtn.setOnClickListener(this);
		userBtn.setOnClickListener(this);
		configBtn.setOnClickListener(this);
		hander.setOnClickListener(this);
		userCenterBtn.setOnClickListener(this);
		
		inAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_right);
		outAnimation = AnimationUtils.loadAnimation(this, R.anim.slide_left);
		outAnimation.setAnimationListener(new AnimationListener() {
			public void onAnimationStart(Animation animation) {}
			public void onAnimationRepeat(Animation animation) {}
			public void onAnimationEnd(Animation animation) {
				WidgetService.newsCenterWidget.setVisibility(View.VISIBLE);
				finish();
			}
		});
		
		aboutDialog = new AlertDialog.Builder(context).
			setCancelable(false)
			.setTitle("关于")
			.setMessage("当前版本为："+getVersionName())
			.setNegativeButton("确定", new android.content.DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}})
			.create();
		
		registerForContextMenu(main);
		openNewsList(R.id.btn_sys);
		clearNewsNum();
		setinAnimation();

	}
	private void refreshUploadInfo(final String path){
		new Thread(new Runnable() {
			public void run() {
				try {
					URL url=new URL(path);
					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(url.openStream(), "UTF-8");
					int event = parser.getEventType();
					while(event!=XmlPullParser.END_DOCUMENT){
						switch (event) {
						case XmlPullParser.START_DOCUMENT:
							info=new UpgradeInfo();
							break;
						case XmlPullParser.START_TAG:
							String tag = parser.getName();
							if ("code".equals(tag)){
								info.code=Integer.parseInt(parser.nextText());
							}else if("description".equals(tag)){
								info.description=parser.nextText();
							}else if("versioncode".equals(tag)){
								info.versioncode=Integer.parseInt(parser.nextText());
							}else if("url".equals(tag)){
								info.url=parser.nextText();
							}else if("must".equals(tag)){
								int b=Integer.parseInt(parser.nextText());
								info.must=b==1;
							}else if("size".equals(tag)) {
								info.size=Long.parseLong(parser.nextText());
							}
							break;
						}
						event=parser.next();
					}
					if (shouldUpload(info.versioncode)) {
						handler.sendEmptyMessage(NEED_UPGRADE);
					}else {
						handler.sendEmptyMessage(DO_NOT_NEED_UPGRADE);
					}
				} catch (Exception e) {
					Log.i("test", "get Upgrade info error",e);
					handler.sendEmptyMessage(UPGRADE_ERROR);
				}
			}
		}).start();
	}
	
	protected static final int NEED_UPGRADE = 0;
	protected static final int DO_NOT_NEED_UPGRADE = 1;
	protected static final int UPGRADE_ERROR = 2;
	protected static final int NEWS_NUM_CHANGED = 3;
	
	private boolean shouldUpload(int remoteVersioncode) throws NameNotFoundException {
		int localVersionCode=getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
		return remoteVersioncode>localVersionCode;
	}
	
	static class UpgradeInfo{
		public int code;
		public String description;
		public int versioncode;
		public String url;
		public boolean must;
		public long size;
		@Override
		public String toString() {
			return "UpgradeInfo [code=" + code + ", description=" + description
					+ ", versioncode=" + versioncode + ", url=" + url
					+ ", must=" + must + ", size=" + size + "]";
		}
	}
	private void showAppUploadWindow() {
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle("版本升级");
		builder.setCancelable(false);
		builder.setMessage(info.description);
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				startDownLoadService();
				dialog.dismiss();
			}
		});
		if (!info.must) {
			builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					init();
					dialog.dismiss();
				}
			});
		}
		builder.create().show();
	}
	
	private void startDownLoadService() {
		stopService(new Intent(this, WidgetService.class));
		stopService(new Intent(this, NetService.class));
		
		Intent intent=new Intent(this, DownLoadService.class);
		intent.putExtra("apk_url", info.url);
		intent.putExtra("size", info.size);
		startService(intent);
		
		finish();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
//		refreshBtnState();
//		notifyNewsNumChanged();
	}
	/**
	 * 更改按钮显示图标
	 */
	public void refreshBtnState() {
		userId = LoginUtil.getUserId(this);
		if (userId==0) {
			appBtn.setButtonDrawable(R.drawable.btn_app_disable);
			userBtn.setButtonDrawable(R.drawable.btn_user_disable);
		}else {
			appBtn.setButtonDrawable(R.drawable.ico_btn_app);
			userBtn.setButtonDrawable(R.drawable.ico_btn_user);
		}
	}
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.hander:
			setOutAnimation();
			break;
		case R.id.btn_sys:
			openNewsList(R.id.btn_sys);
			break;
		case R.id.btn_app:
			clickAppButton();
			break;
		case R.id.btn_user:
			clickUserButton();
			break;
		case R.id.btn_config:
			openConfigPage();
			break;
		case R.id.btn_usercenter:
			openUserCenter();
			break;
		}
	}
	/**
	 * 打开用户中心
	 */
	private void openUserCenter() {
		userId=LoginUtil.getUserId(context);
		if (userId==0) {
			Intent intent=new Intent(context, LoginActivity.class);
			context.startActivityForResult(intent, R.id.btn_usercenter);
			return;
		}
		if (getCurrentActivity() instanceof UserCenterActivity ) {
			}else {
				container.removeAllViews();
				container.addView(getLocalActivityManager().startActivity("usercenter", 
					new Intent(context,UserCenterActivity.class)
							.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
							.getDecorView(),new LayoutParams(350, 768));
		}
	}

	/**
	 * 点击互动消息按钮
	 * 	是否未登录
	 * 		未登录则显示登录对话框
	 * 		登录则走正常流程
	 */
	private void clickUserButton() {
		userId=LoginUtil.getUserId(context);
		if (userId==0) {
			Intent intent=new Intent(context, LoginActivity.class);
			context.startActivityForResult(intent, R.id.btn_user);
		}else {
			openNewsList(R.id.btn_user);
		}
	}

	/**
	 * 点击应用通知按钮
	 * 	是否未登录
	 * 		未登录则显示登录对话框
	 * 		登录则走正常流程
	 */
	private void clickAppButton() {
		userId=LoginUtil.getUserId(context);
		if (userId==0) {
			Intent intent=new Intent(context, LoginActivity.class);
			context.startActivityForResult(intent, R.id.btn_app);
		}else {
			openNewsList(R.id.btn_app);
		}
	}

	private void openNewsList(int id){
		WidgetService.pressBtn=id;
		Activity currentActivity = getCurrentActivity();
		if (currentActivity instanceof NewsListActivity) {
			NewsListActivity newsListActivity=(NewsListActivity) currentActivity;
			newsListActivity.refresh();
		}else {
			container.removeAllViews();
			container.addView(getLocalActivityManager().startActivity("newslist", 
					new Intent(context,NewsListActivity.class)
							.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
							.getDecorView(),new LinearLayout.LayoutParams(350, 768));
		}
		clearNewsNum();
	}
	
	private void openConfigPage() {
		if (getCurrentActivity() instanceof ConfigActivity ) {
			
		}else {
			container.removeAllViews();
			container.addView(getLocalActivityManager().startActivity("config", 
					new Intent(context,ConfigActivity.class)
							.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
							.getDecorView(),new LinearLayout.LayoutParams(350, 768));
		}
	}
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case NEWS_NUM_CHANGED:
				notifyNewsNumChanged();
				break;
			case NEED_UPGRADE:
				showAppUploadWindow();
				break;
			case DO_NOT_NEED_UPGRADE:
				init();
				break;
			case UPGRADE_ERROR:
				if (info!=null&&info.must) {
					finish();	
				}else {
					init();
				}
				break;
			}
		}
	};
	private View main;
	private Animation inAnimation;
	private Animation outAnimation;
	private RadioButton appBtn;
	private RadioButton userBtn;
	private Activity context;
	private RadioButton sysBtn;
	private AlertDialog aboutDialog;
	
	/**
	 * 清空未读消息提示数
	 */
	public void clearNewsNum(){
		final int[] nums=WidgetService.NewsNums;
		switch (WidgetService.pressBtn) {
		case R.id.btn_sys:
			nums[0]=0;
			break;
		case R.id.btn_app:
			nums[1]=0;
			break;
		case R.id.btn_user:
			nums[2]=0;
			break;
		}
		notifyNewsNum();
	}
	
	public void notifyNewsNum() {
		handler.sendEmptyMessage(NEWS_NUM_CHANGED);
	}
	/**
	 * 提示未读消息数目已经改变
	 * @param type
	 */
	private void notifyNewsNumChanged() {
		if (!ConfigUtil.getCloseBroadcastNotify(this, userId)) {
			initNewsNums(sysNews,0);
		}
		initNewsNums(appNews, 1);
		initNewsNums(userNews,2);
	}
	
	private void initNewsNums(TextView textView,int index){
		final int num =WidgetService.NewsNums[index];
		textView.setText(num+"");
		textView.setVisibility(View.INVISIBLE);
		if (num>0) {
			textView.setVisibility(View.VISIBLE);
		}
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		setOutAnimation();
		return super.onTouchEvent(event);
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		if (requestCode==R.id.btn_usercenter&&resultCode==Activity.RESULT_OK) {
			openUserCenter();
			return;
		}
		
		if (resultCode==Activity.RESULT_OK) {
			openNewsList(requestCode);
		}else {
			openNewsList(R.id.btn_sys);
			sysBtn.setChecked(true);
		}
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, 0, 0, "关于");
	}
	@Override
	public boolean onContextItemSelected(MenuItem item) {
		super.onContextItemSelected(item);
		switch (item.getItemId()) {
		case 0:
			aboutDialog.show();
			break;
		}
		return true;
	}
	private String getVersionName(){
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packageInfo = pm.getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES);
			return packageInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		return null;
	}
}
